<template>
  <el-dialog
    ref="formDlg"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="85%"
    append-to-body
    @close="closeDialog"
  >
    <template slot="title">
      <div>
        <span v-text="spaceName" />
        <el-checkbox v-model="childrenCheck" label="选择方案" border @change="changeCheck" />
      </div>
    </template>
    <div class="table-main">
      <div class="table-left">
        <table-box
          ref="refTable"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          table-row-key="id"
          :show-page="false"
          :table-height="400"
          :selected-arry.sync="tableSelected"
          :table-row-class-name="tableRowClassName"
          @row-click="select"
          @selection-change="selectionChangeHandle"
          @data-change="tableDataChange"
        >
          <el-table-column fixed="left" type="selection" reserve-selection :selectable="canSelect" />
        </table-box>
      </div>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="handleSure">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPruductAllData } from '@/api/shopDesign'
import { formaterData } from '@/utils'
import { deepClone } from '@/utils'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'AddProgramModel',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    checked: {
      type: Boolean,
      default: false
    },
    initData: {
      type: Array,
      default: () => []
    },
    programId: {
      type: String,
      default: ''
    },
    spaceName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formaterData,
      isFirst: true,
      allTableData: [],
      mustList: [],
      childrenCheck: false,
      otherFilters: [{ id: 'enable', property: 'enable', value: '1', operator: '=' }, { id: 'dr', property: 'dr', value: '0', operator: '=' }],

      // 待选方案
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configProgramProductSeries/page`,
        onlySearchBar: true,
        tabIndex: 0,
        sort: 'isMustUp',
        order: 'desc',
        pageFlag: false,
        setting: [

          {
            prop: 'seriesName',
            label: '产品系列',
            minWidth: '110'
          },

          {
            prop: 'sampleFunctionSpace',
            label: '上样功能空间',
            minWidth: '110',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'SAMPLE_FUNCTION_SPACE'
            },
            render: (creat, row) => {
              if (!row.sampleFunctionSpace || !this.sampleFunctionSpaceOptions) {
                return
              }
              let list = []
              if (typeof (row.sampleFunctionSpace) === 'string') {
                list = row.sampleFunctionSpace.split(',')
              } else {
                list = row.sampleFunctionSpace
              }
              const arr = []
              this.sampleFunctionSpaceOptions.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            },
            type: 'select'
          },
          {
            prop: 'isMustUp',
            label: '是否必上',
            type: 'select',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: '110'
          },
          {
            prop: 'seriesDesc',
            label: '系列说明',
            minWidth: '110'
          }, {
            prop: 'assortCupboardSeriesName',
            label: '橱柜系列',
            minWidth: '110'
          }, {
            prop: 'bathRoomSeriesName',
            label: '卫浴系列',
            minWidth: '110'
          }
        ],
        btnList: !this.isProduction ? [] : null
      },
      sampleFunctionSpaceOptions: [],
      selectedRows: [], // 多选行
      cancelSelectedRows: [], // 已取消选择的行
      tableSelected: [], // 单选行
      initSelecteds: []
    }
  },
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.tableSelected = []
        this.selectedRows = []
      }
      if (!oldVal && val) {
        this.$refs.refTable.initTableData()
      }
    },
    allTableData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    },
    selectedRows: {
      handler(v) {
        if (v.length > 0) {
          this.childrenCheck = true
          this.allTableData.forEach((row, keyIndex) => {
            const index = this.mustList.findIndex(item => item.id === row.id || item.configProgramSeriesId === row.id)
            if (index > -1) this.$refs.refTable.toggleRowSelection(row, true)
          })
        } else this.childrenCheck = false
      }
    }
  },
  async  created() {
    this.isFirst = false
    getPruductAllData(this.programId).then(res => {
      if (res.success === 1) this.mustList = res.data.records.filter(el => el.isMustUp)
    })
    this.otherFilters.push({ 'property': 'configProgramProductId', 'value': this.programId, 'operator': '=', 'id': 'configProgramProductId' })
    this.initSelecteds = deepClone(this.initData)
    this.childrenCheck = this.checked
    const { SAMPLE_FUNCTION_SPACE } = await getDictByPatchType(['SAMPLE_FUNCTION_SPACE'])
    this.sampleFunctionSpaceOptions = SAMPLE_FUNCTION_SPACE
  },
  methods: {
    select() {
      // if (this.childrenCheck) this.changeCheck(true)
    },
    canSelect(row, index) {
      if (this.childrenCheck && row.isMustUp) return false
      else return true
    },
    currentChange(row) {
      if (row.isMustUp) {
        this.$confirm('当前数据为必上，取消选择将会取消方案的选择, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.childrenCheck = false
          this.selectedRows.forEach(el => {
            this.delSelectedRow(el)
          })
        })
      } else {
        this.delSelectedRow(row)
      }
    },
    changeCheck(data) {
      this.childrenCheck = data
      if (!data) {
        this.selectedRows.forEach(el => {
          this.delSelectedRow(el)
        })
        this.initSelecteds.forEach(el => {
          this.delSelectedRow(el)
        })
        this.selectedRows = []
        this.initSelecteds = []
      } else {
        if (this.selectedRows.length === 0) {
          this.selectedRows = deepClone(this.mustList)
          // this.initSelecteds = deepClone(this.mustList)
        }
      }
    },
    closeDialog() {
      this.$refs.refTable.clearSelection()
      this.selectedRows = [] // 表格多选行
      this.tableSelected = [] // 表格单选行
      this.$emit('update:visible', false)
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(item => item.id === row.id || item.configProgramSeriesId === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    tableDataChange(res) {
      this.allTableData = (res && res.data && res.data.records) || []
      this.allTableData.forEach((row, keyIndex) => {
        const tempArr = this.initSelecteds.filter((v, index) => v.id === row.id || v.configProgramSeriesId === row.id)
        if (tempArr.length > 0) {
          this.$set(row, 'checked', tempArr[0].checked)
          const newRow = { ...row, ...{ keyIndex, checked: tempArr[0].checked }}
          const rowIndex = this.selectedRows.findIndex(v => v.id === row.id || v.configProgramSeriesId === row.id)
          if (rowIndex === -1) {
            this.selectedRows.push(newRow)
            this.$refs.refTable.toggleRowSelection(newRow, true)
          } else {
            this.$set(this.selectedRows, rowIndex, newRow)
          }
        } else {
          const delRow = { ...row, ...{ keyIndex }}
          this.$refs.refTable.toggleRowSelection(delRow, false)
        }
      })
    },
    // 重置当前页已选中数据的复选状态
    reSetTableSelection() {
      // 判断当前表数据中是存在已取消选中的数据，若存在，则取消表格数据的选中
      const delIds = []
      this.cancelSelectedRows.forEach(row => {
        const tmp = this.allTableData.filter(item => item.id === row.id || row.configProgramSeriesId === item.id)
        if (tmp.length > 0) { // 在当前页表格数据中则取消选中
          this.$refs.refTable.toggleRowSelection(tmp[0], false)
          delIds.push(row.id)
        }
      })
      delIds.forEach(id => {
        const index = this.cancelSelectedRows.findIndex(row => row.id === id)
        this.cancelSelectedRows.splice(index, 1)

        if (this.initSelecteds && this.initSelecteds.length) {
          const indexSelect = this.initSelecteds.findIndex(row => row.id === id)
          if (indexSelect > -1) {
            this.initSelecteds.splice(indexSelect, 1)
          }
        }
      })
    },
    selectionChangeHandle(rows) {
      const obj = {}
      // 去重
      rows = rows.reduce(function(item, next) {
        obj[next.id] ? '' : obj[next.id] = true && item.push(next)
        return item
      }, [])
      this.selectedRows = rows
    },
    // 移除已选择方案
    delSelectedRow(row) {
      const tmp = this.allTableData.filter(item => row.id === item.id || row.configProgramSeriesId === item.id)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refTable.toggleRowSelection(tmp[0], false)
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选组织表中删除
        this.cancelSelectedRows.push(row)
        const index = this.selectedRows.indexOf(row)
        this.selectedRows.splice(index, 1)
      }
    },
    handleSure() {
      const rows = this.selectedRows.map(v => {
        // this.$set(v, 'spaceCode', v.configSpaceId)
        return v
      })

      this.$emit('change', rows, this.childrenCheck)
      this.closeDialog()
    }
  }
}
</script>

<style lang='scss' scoped>
.goods_img {
  margin: 5px;
  max-width: 100%;
  max-height: 50px;
  -o-object-fit: cover;
  object-fit: cover;
  vertical-align: middle;
}
  .table-main{
    width: 100%;
    display: flex;
    .table-left{
      width: 50%;
      box-sizing: border-box;
      /deep/ .btn-box{
        display: none;
      }
    }
    .table-right{
      width:50%;
    }
    .table-left{
      flex:1;
      padding-right: 10px;
    }
    .table-right{
      padding-left: 10px;
      .qup-title-box{
        line-height: 28px;
        height: 28px;
        margin-bottom: 10px;
      }
      // padding-top: 38px;
      .table-list-box{
        margin-top: 0;
      }
    }
  }
  /deep/ .pagination-info{
    display: none
  }
</style>
